const admZip = require("adm-zip");
const iconv = require('iconv-lite')
/**
 * 解压文件到目标文件夹
 * @param {*} zipFile 
 * @param {*} destFolder 
 */
function unzip(zipFile, destFolder) {
  var zip = new admZip(zipFile);

  var zipEntries = zip.getEntries();
  for (var i = 0; i < zipEntries.length; i++) {
      var entry = zipEntries[i];
      entry.entryName = iconv.decode(entry.rawEntryName, 'gbk');
  }

  zip.extractAllTo(destFolder, true);
}
// 使用示例
// unzip(
//     "D:\\codeItem\\ieng-client\\build\\extraResources\\project-template\\工业软件-建设类项目BC级.zip",'D:\\codeItem\\ieng-client\\build\\extraResources\\project-template')

// 计算机存储单位之间的关系
function getFileSizeString(bytes) {
  const prefixes = ["B", "KB", "MB", "GB", "TB", "PB"];

  let size = bytes;
  let prefixIndex = 0;

  while (size > 900) {
    // prefer "0.9 KB" to "949 bytes"
    size /= 1024;
    prefixIndex++;
  }

  return Math.round(size * 10) / 10 + " " + prefixes[prefixIndex];
}


const fs = require('fs');
const path = require('path');

/**
 * 删除文件夹及其子文件
 * @param {string} dirPath - The path to the directory to delete.
 * @returns {Promise<void>}
 */
async function deleteFolderRecursive(dirPath) {
  return new Promise((resolve, reject) => {
    fs.readdir(dirPath, (err, files) => {
      if (err) {
        return reject(err);
      }
      
      let count = 0;

      const done = () => {
        if (--count === 0) {
          fs.rmdir(dirPath, err => {
            if (err) {
              return reject(err);
            }
            resolve();
          });
        }
      };

      files.forEach(file => {
        const filePath = path.join(dirPath, file);
        count++;

        fs.stat(filePath, (err, stats) => {
          if (err) {
            return reject(err);
          }

          if (stats.isDirectory()) {
            deleteFolderRecursive(filePath).then(done, reject);
          } else {
            fs.unlink(filePath, err => {
              if (err) {
                return reject(err);
              }
              done();
            });
          }
        });
      });

      // If the directory is empty, fs.readdir returns an empty array
      // and the done function should be called immediately
      if (files.length === 0) {
        done();
      }
    });
  });
}

// Example usage:
// const directoryPath = 'D:\\defineTest\\graduation-project';
const directoryPath = 'D:\\defineTest\\my-electron-app\\dist';
// fs.rmSync(directoryPath, {recursive: true, force: true})
deleteFolderRecursive(directoryPath)
  .then(() => {
    console.log(`Directory ${directoryPath} deleted successfully.`);
  })
  .catch(err => {
    console.error(`Error deleting directory ${directoryPath}:`, err);
  });